import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useUserStore } from '@/stores/useUserStore'

import Layout from '@/layout/Layout.vue'

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'home',
        component: HomeView
      },
      {
        path: 'class-list',
        name: 'class-list',
        component: import('../views/Class/ClassList.vue')
      },
      {
        path: 'student',
        name: 'student',
        component: import('../views/Student/StudentList.vue')
      },
      {
        path: 'student-group',
        name: 'studentGroup',
        component: import('../views/StudentGroup/StudentGroup.vue')
      },
      {
        path: 'add-student',
        name: 'batchAddStudent',
        component: import('../views/Student/BatchAdd.vue')
      },
      {
        path: 'hw',
        name: 'hw',
        component: import('../views/HW/HWList.vue')
      }
    ]
  },
  // 查询班级指定作业的提交情况
  {
    path: '/hw/detail/:classId/:hwId',
    name: 'HWDetail',
    component: import('../views/HW/HWDetail.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: import('../views/Login/Login.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, _from, next) => {
  const infoStr = localStorage.getItem('user')
  const userStore = useUserStore()
  userStore.setInfo(JSON.parse(infoStr || '{}'))

  if (to.name !== 'login' && !infoStr) {
    next({ name: 'login' })
  } else {
    next()
  }
})
// routes: [
//   {
//     path: '/',
//     name: 'home',
//     component: HomeView
//   },
//   {
//     path: '/about',
//     name: 'about',
//     // route level code-splitting
//     // this generates a separate chunk (About.[hash].js) for this route
//     // which is lazy-loaded when the route is visited.
//     component: () => import('../views/AboutView.vue')
//   }
// ]

export default router
